from ui.homepage import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from ui.handle_thread import *


class MainPage(QWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.setWindowTitle("华清AI搬运")
        self.setWindowIcon(QIcon("./pic/favicon.ico"))
        self.setFixedSize(self.width(), self.height())
        self.setStyleSheet("QPushButton{background-color: #008080;border-radius: 10px;color: white;}"
                           "QPushButton:hover{background-color: #006666;}")

        # self.cap = cv2.VideoCapture(global_video_num)
        # if not self.cap.isOpened():
        #     print("Error: Could not open video.")
        #     sys.exit()
        self.thread = HandleThread()
        self.thread.photoSignal.connect(self.photo_show)
        self.thread.identifySignal.connect(self.identify_show)

        self.timer = QTimer()
        self.timer.timeout.connect(self.updateFrame)
        self.timer.start(30)


        # 按钮点击事件
        self.ui.maxBtn.clicked.connect(self.startSlot)
        self.ui.minBtn.clicked.connect(self.startSlot)
        self.ui.fixBtn.clicked.connect(self.startSlot)

    def updateFrame(self):
        ret, frame = self.thread.vs.read()
        if not ret:
            print("Failed to grab frame")
            return

        # Convert the frame from BGR color (OpenCV default) to RGB color
        rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        h, w, ch = rgb_frame.shape
        bytes_per_line = ch * w
        image = QImage(rgb_frame.data, w, h, bytes_per_line, QImage.Format_RGB888)

        # Display the resulting frame
        show_map = QPixmap.fromImage(image).scaled(self.ui.videoLab.size())
        self.ui.videoLab.setPixmap(show_map)

    def startSlot(self):
        sender = self.sender()
        # 获取对象名
        object_name = sender.objectName()
        if object_name == "maxBtn":
            self.ui.toastBrowser.setPlainText('即将开始寻找最大目标并搬运...')
            self.thread.set_move_type(MoveType.MAX_MOVE_TYPE)
        elif object_name == "minBtn":
            self.ui.toastBrowser.setPlainText('即将开始寻找最小目标并搬运...')
            self.thread.set_move_type(MoveType.MIN_MOVE_TYPE)
        elif object_name == "fixBtn":
            num = self.ui.spinBox.value()
            self.ui.toastBrowser.setPlainText(f'即将开始搬运{num}目标...')
            self.thread.set_move_type(MoveType.FIX_MOVE_TYPE, num)
        self.thread.start()

    def photo_show(self):
        self.ui.photoLab.setPixmap(QPixmap("./pic/result.jpg").scaled(self.ui.photoLab.size()))

    def identify_show(self, index):
        img = img_end_list[index]
        height, width = img.shape
        bytes_per_line = width
        q_img = QImage(img.data, width, height, bytes_per_line, QImage.Format_Grayscale8)
        pixmap = QPixmap.fromImage(q_img)
        self.ui.identifyLab.setPixmap(pixmap)